package controllers

import (
	"day01/models"
	beego "github.com/beego/beego/v2/server/web"
)

type StoreController struct {
	beego.Controller
}

type Res struct {
	Code    int         `json:"code"`
	Data    interface{} `json:"data"`
	Message string      `json:"message"`
}

func (c *StoreController) Add() {
	name := c.GetString("name")
	storeName := c.GetString("storeName")
	tel := c.GetString("tel")
	time := c.GetString("time")
	status := c.GetString("status")

	store := models.Store{
		Name:      name,
		StoreName: storeName,
		Tel:       tel,
		Time:      time,
		Status:    status,
	}

	if err := models.DB.Create(&store).Error; err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "添加失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code:    200,
		Data:    store,
		Message: "添加成功",
	}
	c.ServeJSON()
	return
}

func (c *StoreController) List() {

	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	var store []models.Store

	if err := models.DB.Find(&store).Error; err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "查询失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code:    200,
		Data:    store,
		Message: "查询成功",
	}
	c.ServeJSON()
	return
}

func (c *StoreController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	storeName := c.GetString("storeName")
	tel := c.GetString("tel")
	time := c.GetString("time")
	status := c.GetString("status")

	store := models.Store{
		Name:      name,
		StoreName: storeName,
		Tel:       tel,
		Time:      time,
		Status:    status,
	}

	if err := models.DB.Where("id = ?", id).Updates(&store).Error; err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "修改失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code:    200,
		Data:    store,
		Message: "修改成功",
	}
	c.ServeJSON()
	return
}

func (c *StoreController) Del() {
	id, _ := c.GetInt("id")

	if err := models.DB.Delete(&models.Store{}, id).Error; err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "删除失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code:    200,
		Data:    nil,
		Message: "删除成功",
	}
	c.ServeJSON()
	return
}
